package com.jinsi.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jinsi.pojo.EqmFile;
import com.jinsi.pojo.User;
import com.jinsi.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/getPage")
    public Map<String,Object> getPage(@RequestParam(defaultValue = "1") int page,
                                      @RequestParam(defaultValue = "2") int limit,
                                      Integer fid){

        System.out.println(fid);
        PageHelper.startPage(page,limit);
        // 查询所有数据
        List<EqmFile> all = fileService.getAll(fid);
// 注意：不要忘了传
        PageInfo<EqmFile> info = new PageInfo<>(all);

        Map<String,Object> map = new HashMap<>();
        map.put("code","0");
        map.put("msg","成功");
        map.put("count",info.getTotal());
        map.put("data",info.getList());
        return map;
    }


    @RequestMapping("/uploadFile")
    public Map<String,String> uploadFile(MultipartFile file,
                                         Integer fileFolderId,
                                         Integer equipmentId,
                                         HttpSession session){
        System.out.println(fileFolderId);
        System.out.println(equipmentId);

        Map<String,String> map = new HashMap<>();
        // file.getOriginalFilename() 获取上传的文件名
        System.out.println(file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();

        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(substring);

        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();


        // 上传服务器
        File file1 = new File("D:/uploadfile/"+s+substring);

        try {
            // 上传
            file.transferTo(file1);
            //添加到数据库
//            EqmFile


            EqmFile eqmFile = new EqmFile();
            eqmFile.setFileFolderId(fileFolderId);
            eqmFile.setEquipmentId(equipmentId);
            eqmFile.setFileName(s+substring);

            User user = (User) session.getAttribute("loginuser");
            eqmFile.setCreateName(user.getUsername());


            fileService.addFile(eqmFile);


            map.put("state","200");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("state","300");
        }


        return map;
    }

}
